/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.skatiger.jrove.impl.jaxb;

import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;

import org.skatiger.jrove.JroveException;
import org.skatiger.jrove.impl.DefaultViewContext;
import org.skatiger.jrove.impl._RendererProvider;
import org.skatiger.jrove.renderer.Renderer;
import org.skatiger.jrove.util.StringUtils;

public class JaxbRendererProvider implements _RendererProvider {
    private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory
            .getLogger(JaxbRendererProvider.class);
    private static final Map<String, Renderer> _RENDERER_CACHE = new WeakHashMap<String, Renderer>();

    public Renderer getRenderer(DefaultViewContext context, String rendererType) {
        if (StringUtils.isEmpty(rendererType)) {
            return null;
        }
        Renderer renderer = _RENDERER_CACHE.get(rendererType);
        if (renderer == null) {
            Class<Renderer> _rendererType = findRendererType(rendererType);
            try {
                if (_rendererType != null) {
                    renderer = _rendererType.newInstance();
                }
                _RENDERER_CACHE.put(rendererType, renderer);
            } catch (Exception e) {
                throw new JroveException(
                        "create Renderer instance of renderer class "
                                + _rendererType + " exception.", e);
            }
        }
        return renderer;
    }

    private static final Map<String, Class<Renderer>> _RENDERER_CLASSES = new HashMap<String, Class<Renderer>>();

    public static final Class<Renderer> findRendererType(String rendererType) {
        if (logger.isDebugEnabled()) {
            logger.debug("get renderer by class " + rendererType);
        }
        Class<Renderer> _rendererType = _RENDERER_CLASSES.get(rendererType);
        if (_rendererType == null) {
            try {
                _rendererType = JaxbConfigReader.createClass(Renderer.class,
                        rendererType);
                _RENDERER_CLASSES.put(rendererType, _rendererType);
                logger.debug("found rendererType " + _rendererType.getName());
            } catch (Exception e) {
                logger.warn("get renderer class exception. ", e);
            }
        }
        return _rendererType;
    }
}
